package com.loop.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author zhangxiaolu
 * @since 2023-09-16 21:51
 */
public class WebSocketServer {

    public static void main(String[] args) {
        // 创建两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))// 增加一个日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 因为基于Http协议，使用http解码和解码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            // 是以块方式写，添加ChunkedWriteHandler处理器
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            /*
                            说明：
                            1. http数据在传输过程中是分段的，HttpObjectAggregator,就可以将多个段聚合
                            2. 这就是为什么，当浏览器发送大量数据时，就会发出多次http请求
                             */
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            /*
                            说明：
                            1. 对于webSocket，它的数据是以帧（Frame）形式传递，而不是像Http那样以文本形式传递
                            2. 可以看到WebSocketFrame下面有六个子类
                            3. 浏览器请求时：ws://localhost:8081/xxx 表示请求的uri
                            3. WebSocketServerProtocolHandler核心功能是将http协议升级为ws协议，保持长连接
                             */
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/hello"));
                            // 添加自定义handler
                            ch.pipeline().addLast(new WebSocketFrameHandler());
                        }
                    });
            // 启动服务器
            ChannelFuture future = bootstrap.bind(8081).sync();
            // 监听服务器关闭监听
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
